package com.hemaapp.yjnh.activity;

import java.io.IOException;
import java.util.Hashtable;
import java.util.Vector;

import org.json.JSONException;
import org.json.JSONObject;

import xtom.frame.util.XtomToastUtil;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.DecodeHintType;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.hemaapp.hm_FrameWork.dialog.HemaButtonDialog;
import com.hemaapp.yjnh.BaseUtil;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.utils.PermissionUtils;
import com.hemaapp.yjnh.utils.StatusBarUtil;
import com.hemaapp.yjnh.view.YjnhImageWay;
import com.hemaapp.yjnh.zxing.camera.CameraManager;
import com.hemaapp.yjnh.zxing.decoding.CaptureActivityHandler;
import com.hemaapp.yjnh.zxing.decoding.InactivityTimer;
import com.hemaapp.yjnh.zxing.decoding.RGBLuminanceSource;
import com.hemaapp.yjnh.zxing.view.ViewfinderView;

/**二维码扫描界面
 * @author GuiyouZhang
 * Date：2015年10月27日 下午3:23:45
 * Email:guiyouzhang@163.com
 */
@SuppressLint("HandlerLeak") @SuppressWarnings("deprecation")
public class CodeCaptureActivity extends Activity implements Callback {

	private final int REQUEST_PERMISSION_CAMERA = 0x101;

	private TextView titleText;
	private ImageButton titleLeft;

	private CaptureActivityHandler handler;
	private ViewfinderView viewfinderView;
	private boolean hasSurface;
	private Vector<BarcodeFormat> decodeFormats;
	private String characterSet;
	private InactivityTimer inactivityTimer;
	private TextView tv_album;//相册按钮
	private TextView tv_light;//开灯按钮
	private int sign;

	public YjnhImageWay imageWay;
	private static final int CAMERA = 100;
	private static final int PARSE_BARCODE_SUC = 300;
	private static final int PARSE_BARCODE_FAIL = 303;
	private ProgressDialog mProgress;
	private String photo_path;
	private Bitmap scanBitmap;
	
	private String imagePathCamera;

	@SuppressLint("CutPasteId") @Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_capture);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // 设置状态栏透明
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            // 获得状态栏高度
            int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
            int statusBarHeight = getResources().getDimensionPixelSize(resourceId);
            FrameLayout layoutTitle = (FrameLayout) findViewById(R.id.layout_title);
            FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) layoutTitle.getLayoutParams();
            params.setMargins(0, statusBarHeight, 0, 0);
        }
		initView();
		if (savedInstanceState == null) {
			imageWay = new YjnhImageWay(this, CAMERA, 2);
		} else {
			imagePathCamera = savedInstanceState.getString("imagePathCamera");
			imageWay = new YjnhImageWay(this, CAMERA, 2);
		}
		CameraManager.init(getApplication());
		hasSurface = false;
		inactivityTimer = new InactivityTimer(this);
		viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);

		tv_light = (TextView) findViewById(R.id.tv_light);
		tv_album = (TextView) findViewById(R.id.tv_album);
		//开灯监听
		tv_light.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
                try {
                    if (sign % 2 == 0) {
                        CameraManager.get().openF();
                        tv_light.setText("关灯");
                    } else {
                        CameraManager.get().stopF();
                        tv_light.setText("开灯");
                    }
                    sign++;
                }catch(Exception e) {
                    e.printStackTrace();
                    XtomToastUtil.showShortToast(CodeCaptureActivity.this, "请在权限管理中打开相机权限");
                    PermissionUtils.gotoMiuiPermission(CodeCaptureActivity.this);
                }
			}
		});
		//相册监听
		tv_album.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				//打开手机中的相册
				imageWay.album();
			}
		});
	}

	private void initView() {
		titleText = (TextView) findViewById(R.id.title_text);
		titleLeft = (ImageButton) findViewById(R.id.title_left_btn);
		titleText.setText("扫一扫");
		titleLeft.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

	private Handler mHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);

			mProgress.dismiss();
			switch (msg.what) {
			case PARSE_BARCODE_SUC:
				onResultHandler((String)msg.obj, scanBitmap);
				break;
			case PARSE_BARCODE_FAIL:
				Toast.makeText(CodeCaptureActivity.this, (String)msg.obj, Toast.LENGTH_LONG).show();
				break;

			}
		}
	};

	/**
	 * 处理扫描相册结果，跳转到上一个页面
	 * @param resultString
	 * @param bitmap
	 */
	private void onResultHandler(String resultString, Bitmap bitmap){
		if(TextUtils.isEmpty(resultString)){
			Toast.makeText(CodeCaptureActivity.this, "扫描失败！", Toast.LENGTH_SHORT).show();
			return;
		}
		if (resultString.startsWith("http")) {
			Intent itScan = new Intent(getApplicationContext(), WebviewActivity.class);
			itScan.putExtra("parm", resultString);
			itScan.putExtra("type", 6);
			startActivity(itScan);
		}else {
			if (!BaseUtil.isLogin()) {
				XtomToastUtil.showShortToast(getApplicationContext(), "请先登录");
				return;
			}
			String keytype = null, username = null;
			JSONObject jsonObject;
			try {
				jsonObject = new JSONObject(resultString);
				if (!jsonObject.isNull("keytype")) {
					keytype = jsonObject.getString("keytype");
				}
				if (!jsonObject.isNull("username")) {
					username = jsonObject.getString("username");
				}
				Intent itCoupon = new Intent(getApplicationContext(), TransferActivity.class);;
				itCoupon.putExtra("keytype", keytype);
				itCoupon.putExtra("accout", username);
				startActivity(itCoupon);
			} catch (JSONException e) {
				e.printStackTrace();
				XtomToastUtil.showShortToast(getApplicationContext(), "未能识别的二维码");
			}
		}
		finish();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode == RESULT_OK){
			switch(requestCode){
			case CAMERA:
				//获取选中图片的路径
				Cursor cursor = getContentResolver().query(data.getData(), null, null, null, null);
				if (cursor != null) {
					if (cursor.moveToFirst()) {
						photo_path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
					}
					cursor.close();
				}else {
					Toast.makeText(getApplicationContext(), "无法获取图片！", Toast.LENGTH_SHORT);
					break;
				}
					
				mProgress = new ProgressDialog(CodeCaptureActivity.this);
				mProgress.setMessage("正在扫描...");
				mProgress.setCancelable(false);
				mProgress.show();

				new Thread(new Runnable() {
					@Override
					public void run() {
						Result result = scanningImage(photo_path);
						if (result != null) {
							Message m = mHandler.obtainMessage();
							m.what = PARSE_BARCODE_SUC;
							m.obj = result.getText();
							mHandler.sendMessage(m);
						} else {
							Message m = mHandler.obtainMessage();
							m.what = PARSE_BARCODE_FAIL;
							m.obj = "扫描失败";
							mHandler.sendMessage(m);
						}
					}
				}).start();

				break;

			}
		}
	}
	/**
	 * 扫描二维码图片的方法
	 * @param path
	 * @return
	 */
	public Result scanningImage(String path) {
		if(TextUtils.isEmpty(path)){
			return null;
		}
		Hashtable<DecodeHintType, String> hints = new Hashtable<DecodeHintType, String>();
		hints.put(DecodeHintType.CHARACTER_SET, "UTF8"); //设置二维码内容的编码

		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true; // 先获取原大小
		scanBitmap = BitmapFactory.decodeFile(path, options);
		options.inJustDecodeBounds = false; // 获取新的大小
		int sampleSize = (int) (options.outHeight / (float) 200);
		if (sampleSize <= 0)
			sampleSize = 1;
		options.inSampleSize = sampleSize;
		scanBitmap = BitmapFactory.decodeFile(path, options);
		RGBLuminanceSource source = new RGBLuminanceSource(scanBitmap);
		BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source));
		QRCodeReader reader = new QRCodeReader();
		try {
			return reader.decode(bitmap1, hints);

		} catch (NotFoundException e) {
			e.printStackTrace();
		} catch (ChecksumException e) {
			e.printStackTrace();
		} catch (FormatException e) {
			e.printStackTrace();
		}
		return null;
	}
	@Override
	protected void onResume() {
		super.onResume();
		SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
		SurfaceHolder surfaceHolder = surfaceView.getHolder();
		if (hasSurface) {
			initCamera(surfaceHolder);
		} else {
			surfaceHolder.addCallback(this);
			surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		}
		decodeFormats = null;
		characterSet = null;

		AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
		if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
		}
        //判断相机权限
        if (ContextCompat.checkSelfPermission(CodeCaptureActivity.this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            final HemaButtonDialog dialog = new HemaButtonDialog(CodeCaptureActivity.this);
            dialog.setText("请在权限管理中打开相机权限");
            dialog.setRightButtonText("设置");
            dialog.setButtonListener(new HemaButtonDialog.OnButtonListener() {
                @Override
                public void onLeftButtonClick(HemaButtonDialog hemaButtonDialog) {
                    dialog.cancel();
                    finish();
                }

                @Override
                public void onRightButtonClick(HemaButtonDialog hemaButtonDialog) {
                    dialog.cancel();
                    PermissionUtils.gotoMiuiPermission(CodeCaptureActivity.this);
                }
            });
        }
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (handler != null) {
			handler.quitSynchronously();
			handler = null;
		}
		CameraManager.get().closeDriver();
	}

	@Override
	protected void onDestroy() {
		inactivityTimer.shutdown();
		super.onDestroy();
	}

	/**
	 * 处理扫描结果
	 * @param result
	 * @param barcode
	 */
	public void handleDecode(Result result, Bitmap barcode) {
		inactivityTimer.onActivity();
		String resultString = result.getText();
		if (resultString.equals("")) {
			Toast.makeText(CodeCaptureActivity.this, "扫描失败！", Toast.LENGTH_SHORT).show();
			return;
		}

		if (resultString.startsWith("http")) {
			Intent itScan = new Intent(getApplicationContext(), WebviewActivity.class);
			itScan.putExtra("parm", resultString);
			itScan.putExtra("type", 6);
			startActivity(itScan);
		}else {
			if (!BaseUtil.isLogin()) {
				XtomToastUtil.showShortToast(getApplicationContext(), "请先登录");
				return;
			}
			String keytype = null, username = null;
			JSONObject jsonObject;
			try {
				jsonObject = new JSONObject(resultString);
				if (!jsonObject.isNull("keytype")) {
					keytype = jsonObject.getString("keytype");
				}
				if (!jsonObject.isNull("username")) {
					username = jsonObject.getString("username");
				}
				Intent itCoupon = new Intent(getApplicationContext(), TransferActivity.class);;
				itCoupon.putExtra("keytype", keytype);
				itCoupon.putExtra("accout", username);
				startActivity(itCoupon);
			} catch (JSONException e) {
				e.printStackTrace();
				XtomToastUtil.showShortToast(getApplicationContext(), "未能识别的二维码");
			}
		}
		finish();
	}

	private void initCamera(SurfaceHolder surfaceHolder) {
		try {
			CameraManager.get().openDriver(surfaceHolder);
		} catch (IOException ioe) {
			return;
		} catch (RuntimeException e) {
			return;
		}
		if (handler == null) {
			handler = new CaptureActivityHandler(this, decodeFormats,
					characterSet);
		}
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {

	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		if (!hasSurface) {
			hasSurface = true;
			initCamera(holder);
		}

	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		hasSurface = false;

	}

	public ViewfinderView getViewfinderView() {
		return viewfinderView;
	}

	public Handler getHandler() {
		return handler;
	}

	public void drawViewfinder() {
		viewfinderView.drawViewfinder();

	}

}